var app = getApp()
import api from '../../api/api'
import {
  weixinopenlogin
} from '../../api/conf'
import {
  customer
} from '../../api/conf'
import {
  uploadavatar
} from '../../api/conf'

Page({

  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  onLoad: function(options) {

  },

  onReady: function() {

  },

  onShow: function() {

  },
  bindGetUserInfo: function(e) {
    let that = this;
    let info = e;
    if (info.detail.userInfo) {
      wx.login({
        success: function(res) {
          if (res.code) {
            api.get(weixinopenlogin, {
              code: res.code,
              guid: wx.getStorageSync('guid'),
              encryptedData: info.detail.encryptedData,
              iv: info.detail.iv,
              state: wx.getStorageSync('code')
            }).then(data => {
              if (data.Code == 200) {
                wx.setStorageSync('guid', data.Data.guid)
                wx.setStorageSync('token', data.Data.token)
                wx.setStorageSync('openId', data.Data.openId)
                wx.showToast({
                  title: '登录成功',
                  icon: 'succes',
                  duration: 1000,
                  mask: true
                })

                wx.getUserInfo({
                  success: function(data) {
                    api.post(customer, {
                      "Nickname": data.userInfo.nickName
                    }).then((res) => {
                      wx.setStorageSync('Nickname', data.userInfo.nickName)
                    })

                    wx.request({
                      url: data.userInfo.avatarUrl,
                      responseType: 'arraybuffer', //最关键的参数，设置返回的数据格式为arraybuffer
                      success: res => {
                        //把arraybuffer转成base64
                        let base64 = wx.arrayBufferToBase64(res.data);

                        //不加上这串字符，在页面无法显示的哦
                        base64 = 'data:image/jpeg;base64,' + base64
                       
                        api.post(uploadavatar, {
                          "base64Str": base64
                        }).then((res) => {
                          wx.setStorageSync('avatarUrl', res.Data.AvatarUrl)
                        })

                      }
                    })








                  }
                })

                wx.navigateBack()
              } else {
                wx.showToast({
                  title: '登录失败，请重试！',
                })
              }
            })
          } else {
            wx.showToast({
              title: '微信授权登录失败，请重试！',
            })
          }
        },
      })
    } else {
      console.log("点击了拒绝授权");
    }
  }

})